package com.mihuo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步任务线程池配置类
 * 配置自定义的线程池用于Spring异步任务执行，优化系统异步处理性能
 *
 * @author mihuo
 * @version 1.0
 * @since 2025/09/30
 */
@Configuration
public class AsyncConfig {

    @Bean("customTaskExecutor")
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数，即使空闲也保留的线程数量
        executor.setCorePoolSize(5);
        // 最大线程数，队列满后能创建的最大线程数
        executor.setMaxPoolSize(10);
        // 队列容量，核心线程忙时新任务的等待队列
        executor.setQueueCapacity(100);
        // 非核心线程空闲存活时间（秒）
        executor.setKeepAliveSeconds(60);
        // 线程名称前缀，便于日志追踪
        executor.setThreadNamePrefix("Async-Thread-");
        // 拒绝策略：当最大线程数和队列都满时如何处理新任务
        // CallerRunsPolicy: 由调用者线程直接执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 优雅关闭：等待所有任务完成后关闭
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 关闭等待最大时间
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();
        return executor;
    }
}